﻿using LibPlug.Model;
using Newtonsoft.Json.Linq;
using System;

namespace BiliBiliLiveDanMuTool.Utils
{
    /// <summary>
    /// 协议解析
    /// </summary>
    public class DataAssembler
    {
        private JObject m_jsonObject;

        /// <summary>
        /// 协议解析
        /// </summary>
        /// <param name="msg">需要解析的信息</param>
        public DataAssembler(string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                throw new NullReferenceException();
            }
            m_jsonObject = JObject.Parse(msg);
        }

        /// <summary>
        /// 获得当前消息
        /// </summary>
        /// <returns></returns>
        public DanMuMessageModel GetMessage()
        {
            if (m_jsonObject == null) return null;
            string _cmd = m_jsonObject["cmd"].ToString();

            switch (_cmd)
            {
                case "DANMU_MSG": // 弹幕
                    JArray _jInfo = JArray.Parse(m_jsonObject["info"].ToString());
                    string _content = _jInfo[1].ToString();
                    string _user = JArray.Parse(_jInfo[2].ToString())[1].ToString();
                    return new DanMuMessageModel() { User = _user,Content = _content,Type = MessageType.Normal};
                case "SEND_GIFT": // 礼物
                    JObject _jObject = JObject.Parse(m_jsonObject["data"].ToString());
                    _user = _jObject["uname"].ToObject<string>();
                    string _giftName = _jObject["giftName"].ToString();
                    int _num = _jObject["num"].ToObject<int>();
                    return new DanMuMessageModel() { User = _user, Content = string.Format("赠送了{0}个{1}", _num, _giftName), Type = MessageType.Gift };
                case "WELCOME": // 用户进入
                    _jObject = JObject.Parse(m_jsonObject["data"].ToString());
                    _user = _jObject["uname"].ToString();
                    return new DanMuMessageModel() { User = _user, Content = "进入了直播间~", Type = MessageType.WelCome };
                default:
                    return null;
            }
        }
    }
}
